import React, { Component } from 'react';
// import { Header, List, Segment, Grid, Image, Statistic, Form } from 'semantic-ui-react'
// import { Button, Navbar, ListGroup, ListGroupItem} from 'react-bootstrap';
import { Flex, Button, List, NavBar, InputItem, Picker, Stepper, Icon, WhiteSpace } from 'antd-mobile';
import { BrowserRouter as Router, Route, Redirect } from "react-router-dom";
import axios from 'axios-jsonp-pro';
// import MockAdapter from 'axios-mock-adapter';
import logo from './logo.svg';
import './App.css';

// let mockAdapter = new MockAdapter(axios);
//      mockAdapter.onGet('/price').reply(200, {
//        price: [{binance:700}, {okex:600}, {huobi:600}, {kraken:600}, {poloniex:600}]
//      });

const Item = List.Item;
     const Brief = Item.Brief;

const CustomIcon = ({ type, className = '', size = 'md', ...restProps }) => {
  return (
    <svg
      className={`am-icon am-icon-${type.default.id} am-icon-${size} ${className}`}
      {...restProps}
    >
      <use xlinkHref={`#${type.default.id}`} />
    </svg>
  )
};

// axios.defaults.baseURL = 'http://127.0.0.1:11666/coinpital';
axios.defaults.baseURL = 'http://18.218.108.114:11666/coinpital';
// api 接口示例： http://172.31.39.247:11666/coinpital/price?market=binance&coin=eth&base=btc
// {‘price’:7600.987}

// 有三个参数 
// market： 可以为 binance  okex  huobi kraken  poloniex  其中之一
// coin：币的名字 例如 eth  eos  btc
// base：计价单元 例如 btc  usdt

const baseOptions = [
  { key: 'b', text: 'BTC', value: 'btc' },
  { key: 'u', text: 'USD', value: 'usdt' },
]

const cryptoOptions = [
  { key: 'btc', text: 'BTC', value: 'btc' },
  { key: 'eth', text: 'ETH', value: 'eth' },
  { key: 'eos', text: 'EOS', value: 'eos' },
]

const marketOptions = [
  { key: 'b', text: 'Binance', value: 'binance', ico:'./images/binance.png'},
  { key: 'o', text: 'OKEX', value: 'okex', ico:'./images/okex.png' },
  { key: 'h', text: 'Huobi', value: 'huobi', ico:'./images/huobi.png' },
  { key: 'k', text: 'kraken', value: 'kraken', ico:'./images/kraken.jpeg' },
  { key: 'p', text: 'Poloniex', value: 'poloniex', ico:'./images/poloniex.png' },
]

const pickBaseOptions = baseOptions.map((item, i) =>
  {return {value:item.value, label:item.text}}
);

const pickCryptoOptions = cryptoOptions.map((item, i) =>
  {return {value:item.value, label:item.text}}
);

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let moneyKeyboardWrapProps;
if (isIPhone) {
  moneyKeyboardWrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

// class CoinInitForm extends Component {
//   constructor(props) {
//     super(props);
//     this.state = {formData: {...props.formData}};
//   }

//   onFormChange(){

//   }

//   formSearch(){
    
//   }

//   render() {
//     return (
//       <form>
//       <List renderHeader={() => 'Basic'}
//         // renderFooter={() => getFieldError('account') && getFieldError('account').join(',')}
//       >
//         <Picker data={pickBaseOptions} cols={1} onChange={this.onFormChange}>
//           <Item arrow='down'>Base Currency</Item>
//         </Picker>
//         <InputItem 
//           type="money"
//           placeholder="点击输入"
//           moneyKeyboardWrapProps={moneyKeyboardWrapProps}
//         >Amount</InputItem>
//       </List>
//       <List renderHeader={() => 'Crypto'}
//       >
//         <Picker data={pickCryptoOptions} cols="1">
//           <Item arrow='down'> </Item>
//         </Picker>
//         <Picker data={pickCryptoOptions} cols="1">
//           <Item arrow='down'> </Item>
//         </Picker>
//       </List>
//       <input type="submit" value="Search" />
//       {/* <Button onClick={this.formSearch} >Search</Button> */}
//     </form>
//     );
//   }
// }

const formStateHelper = function(formData){
  let formState = {};
  if (formData.hasOwnProperty('base')) {
    const pickBaseOp = pickBaseOptions.find(function(baseItem){
      return baseItem.value === formData.base
    })
    formState["base"] = [pickBaseOp.value, pickBaseOp.label];
  }

  if (formData.hasOwnProperty('crypto')) {
    const pickCryptoOp = pickCryptoOptions.find(function(cryptoItem){
      return cryptoItem.value === formData.crypto
    })
    formState["crypto"] = [pickCryptoOp.value, pickCryptoOp.label];
  }

  if (formData.hasOwnProperty('amount')) {
    formState["amount"] = formData.amount
  }

  console.log(formState)
  return {...formState};
}

class CoinForm extends Component {
  constructor(props) {
    super(props);
    if (props.hasOwnProperty('formData')) {
      this.state = formStateHelper({...props.formData});
    } else {
      if (window.globalData.hasOwnProperty('formData')) {
        this.state = formStateHelper({...window.globalData.formData});
      } else {
        // this.props.history.push('/init');
        this.state = {}
      }
    }
    this.formCommit = this.formCommit.bind(this);
  }

  handleInputChange(event) {
    console.log(event)
    // const target = event.target;
    // const value = target.value;
    // const name = target.name;

    // this.setState({
    //   [name]: value
    // });
  }

  formCommit(){
    console.log(this.state)
    window.globalData = {'formData':{base:this.state.base[0], crypto:this.state.crypto[0], amount:this.state.amount}}
    this.props.history.push('/search');
  }

  render() {
    console.log(this.state)
    return (
      <div>
      <List renderHeader={() => 'Basic'}
        // renderFooter={() => getFieldError('account') && getFieldError('account').join(',')}
      >
        <Picker data={pickBaseOptions} cols={1} onChange={v => this.setState({ base: v })} value={this.state.base} >
          <Item arrow='down'>Base Currency</Item>
        </Picker>
        <InputItem 
          value={this.state.amount}
          type="money"
          placeholder="点击输入"
          moneyKeyboardWrapProps={moneyKeyboardWrapProps}
          onChange={v => this.setState({ amount: v })}
        >Amount</InputItem>
      </List>
      <List renderHeader={() => 'Crypto'}
      >
        <Picker data={pickCryptoOptions} cols="1"  value={this.state.crypto} onChange={v => this.setState({ crypto: v })} >
          <Item arrow='down'> </Item>
        </Picker>
        {/* <Picker data={pickCryptoOptions} cols="1">
          <Item arrow='down'> </Item>
        </Picker> */}
      </List>
      
      {/* <List renderHeader={() => ' '}
        // renderFooter={() => getFieldError('account') && getFieldError('account').join(',')}
      >
        <Item wrap extra={ 
          <Stepper 
            style={{ width: '100%', minWidth: '100px' }} 
            defaultValue="1"
            showNumber 
            max={100} 
            min={1} 
          />
        } >Invested % of BTC</Item>
        <Item extra="3,500"><Brief>Estimated USD</Brief> </Item>
        <Item wrap extra={
          <Stepper 
            style={{ width: '100%', minWidth: '100px' }}
            defaultValue="1"
            showNumber 
            max={100} 
            min={1} 
          />
        } >Invested % of BTC</Item>
        <Item extra="3,500"><Brief>Estimated USD</Brief> </Item>
      </List> */}
      <WhiteSpace />
      {/* <input type="submit" value="Search" /> */}
      <Button onClick={this.formCommit} >Search</Button>
      </div>
    );
  }
}

// class AppInitPage extends Component {
//   render() {
//     return (
//       <div>
//         <CoinForm formData={{amount:350, base:['usdt'], crypto:['eth']}} />
//         {/* <Button>Search</Button> */}
//       </div>
//     )
//   }
// }

class SearchList extends Component {
  constructor(props){
    super(props);
    this.state = {priceArray:[]};
  }

  componentDidMount() {
    let currentComponent = this;
    const formData = window.globalData.formData;
    // axios.all(
    //   marketOptions.map((market, i) =>
    //   //?market=binance&coin=eth&base=btc
    //     axios.jsonp('/price', {
    //       params:{market:market.value, coin:formData.crypto, base:formData.base}})
    //   )
    // )
    // .then(axios.spread(function (...resArrary) {
    // // Both requests are now complete
    //   console.log("resArrary");
    //   console.log(resArrary);
    //   const infoArray = resArrary.map((res) => {return {...res.config.params, ...res.data}})
    //   console.log(infoArray);
    //   currentComponent.setState({priceArray:infoArray})
    //  })
    // );
    var lineArray = marketOptions.map((market, i) => market.value);
    var csvContent = lineArray.join(",");
    axios.get('/price', {params:{coin:formData.crypto, base:formData.base, market:csvContent}})
    .then(function (response) {
      console.log(response.data.price);
      let obj = {}; 
      for(let i = 0; i < response.data.price.length; i++) { Object.assign(obj, response.data.price[i]) }
      const infoArray = marketOptions.map(function(market){return {market:market.value, coin:formData.crypto, base:formData.base, price:obj[market.value]}})
      console.log(infoArray);
      currentComponent.setState({priceArray:infoArray})
    })
    .catch(function (error) {
      console.log(error);
    });
  }

  render() {
    console.log(window.globalData)
    const formData = window.globalData.formData;
    const listItems = this.state.priceArray.map((item, i) =>
      <List.Item key={i} 
        // onClick={() => {this.props.history.push('/price/'+i)}}
        >
        <CoinItem data={item} likey={i+1} />
      </List.Item>
    );
    // const detailItem = mock[0]
    const baseOp = baseOptions.find(function(baseItem){
      return baseItem.value === formData.base
    })

    const cryptoOp = cryptoOptions.find(function(cryptoItem){
      return cryptoItem.value === formData.crypto
    })
    return (
      <div>
        <div style={{paddingTop:'25px', paddingLeft:'15px', height:'40px'}}>
        <span>{formData.amount} {baseOp.text} {'->'} {cryptoOp.text}</span>
        <a href="/priceForm" style={{backgroundColor:'white', marginLeft:'5px', padding:'3px', border: '2px solid grey', borderRadius:'10px', active:{color:'black'}}}>edit</a>
        {/* <CustomIcon type={require('./assets/icons/personal.svg')} /> */}
        <div>
        </div>
        </div>
        <div> <List>{listItems}</List></div>
      </div>
    );
  }
}

class CoinItem extends Component {
  render() {

    const formData = window.globalData.formData;
    let currentComponent = this;
    console.log(this.props.data)
    const baseOp = baseOptions.find(function(baseItem){
      return baseItem.value === currentComponent.props.data.base
    })

    const cryptoOp = cryptoOptions.find(function(cryptoItem){
      return cryptoItem.value === currentComponent.props.data.coin
    })

    const marketOp = marketOptions.find(function(marketItem){
      return marketItem.value === currentComponent.props.data.market
    })

    return (
      <div style={{}}>
      <div style={{}}>
    <Flex justify="between">
        <div style={{width:'10px', height:'10px', position:'absolute', top:'0', left:'0'}}>{this.props.likey}</div>
        <div style={{paddingLeft:'30px'}}>
          <img style={{display: 'block',marginLeft: 'auto', marginRight:'auto', marginTop:'20px'}} src={marketOp.ico}/>
          <p style={{fontSize: '16px',textAlign: 'center', width:'100%'}}>{marketOp.text}</p>
        </div>
        {/* <div>
          <p>其他渠道</p>
          <p><span>{this.props.data.price}</span><span>{this.props.data.crypto.text}</span></p>
        </div> */}
        <div style={{textAlign: 'center'}}>
          <p style={{fontSize: '16px'}}>到手价</p>
          <p style={{fontSize: '16px', marginTop:'-17px'}}>
            <span style={{color:'#00A1FF', margin:'5px'}} >{this.props.data.price * formData.amount}</span>
            <span>{cryptoOp.text}</span>
          </p>
          {/* <p>含转到钱包成本</p> */}
        </div>
      </Flex>
        </div>
        </div>
    );
  }
}

class CoinSubItem extends Component {
  render() {
    return (
      <Flex justify="between" >
        <div>
          <p>{this.props.data.market.text}</p>
          <p><span>{this.props.data.price}</span><span>{this.props.data.crypto.text}</span></p>
        </div>
        <div>
          <p>中间服务费用</p>
          <p><span>{this.props.data.price}</span><span>{this.props.data.crypto.text}</span></p>
          <p><span>{'-'}{this.props.data.price}</span><span>{this.props.data.base.text}</span></p>
        </div>
        <div>
          <p>转到钱包时间</p>
          <p><span>1.5</span><span>天</span></p>
          <p></p>
        </div>
      </Flex>
    );
  }
}

// class DetailPage extends Component {
//   render() {
//     const listItems = this.props.data.map((item, i) =>
//     <List.Item key={i} onClick={() => {}}>
//       <CoinSubItem data={item} />
//     </List.Item>
//     );

//     const detailItem = this.props.detailItem
//     return (
//       <div>
//         <div>
//         <span>{detailItem.amount} {detailItem.base.text} {'->'} {detailItem.crypto.text}</span>
//         </div>
//         <div>
//           <List>
//           <List.Item extra={<Button type="primary" size="small" inline>Trade</Button>}>
//           <div>
//             <CoinItem data={detailItem}/>
//           </div>
//           </List.Item>
//           {listItems}
//           <List.Item>
//             <span>Show less</span>
//           </List.Item>
//           </List>
//       <Flex justify="between">
//         <div>
//           <img src={detailItem.market.ico}/>
//         </div>
//           <div>
//             <p>交易后</p>
//             <p><span>{detailItem.price}</span><span>{detailItem.text}</span></p>
//           </div>
//           <div>
//             <p>提出费</p>
//             <p><span>{detailItem.price}</span><span>{detailItem.crypto.text}</span></p>
//           </div>
//           <div>
//             <p>到手价</p>
//             <p><span>{detailItem.price}</span><span>{detailItem.text}</span></p>
//             <p>含转到钱包成本</p>
//           </div>
//         </Flex>
//         </div>
        
       
//       </div>
//     );
//   }
// }

// const DetailPageWrap = ({ match }) => (
//   <DetailPage data={mock} detailItem={mock[match.params.id]}/>
// );

class indexWrap extends React.Component {
  render() {
    console.log(window.globalData);
    if (window.globalData.hasOwnProperty('formData')) {
      this.props.history.push('/search');
    } else {
      this.props.history.push('/init');
    }
    return (
      <div>载入中...</div>
    )
  }
}

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      window.globalData.hasOwnProperty('formData') ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/init",
            // state: { from: props.location }
          }}
        />
      )
    }
  />
);

class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <NavBar
            mode="dark"
            // icon={<Icon type="left" />}
            // rightContent={<CustomIcon type={require('./assets/icons/personal.svg')} />}
          >Coinpital</NavBar>
          <Route exact path="/" component={indexWrap} />
          <PrivateRoute path="/search" component={SearchList} />
          <Route path="/priceForm" component={CoinForm} />
          {/* <Route path="/price/:id" component={DetailPageWrap} /> */}
          <Route path="/init" component={CoinForm} />
        </div>
      </Router>
    );
  }
}

export default App;
